'use client'
import type { Chat } from '@/app/im-system/chat/layout'
import { useDrag } from '@/contexts/DragContext'
import { useWebSocket } from '@/hooks/useWebSocket'
import { useChatMessageStore } from '@/store/chatMessage'
import { useUserStore } from '@/store/user'
import { WSMessageType } from '@/types/ws'
import request from '@/utils/frontend/request'
import { FileOutlined, PictureOutlined, SendOutlined, SmileOutlined } from '@ant-design/icons'
import { Avatar, Badge, Button, Input, List, message } from 'antd'
import { useParams } from 'next/navigation'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useChatStore } from '@/store/chat'

export default function ChatDetailPage() {
	const params = useParams()
	const chatId = params.id // 获取路由参数
	const { userInfo } = useUserStore()
	const [messageInput, setMessageInput] = useState('')
	const [isClient, setIsClient] = useState(false)
	const { activeChat, setActiveChat } = useChatStore()
	const { getChatMessages, setMessages } = useChatMessageStore()
	const chatMessages = getChatMessages(Number(chatId))
	const { frontendSendWsEvent } = useWebSocket()
	const messagesEndRef = useRef<HTMLDivElement>(null)

	useEffect(() => {
		const storedChat = localStorage.getItem('activeChat')
		if (storedChat) {
			const chat = JSON.parse(storedChat) as Chat
			setActiveChat(chat)
		}
	}, [])

	const { handleMouseDown } = useDrag()

	// 获取历史消息
	const fetchMessages = useCallback(async () => {
		try {
			const { success, data } = (await request.get(`/chat/${chatId}/messages`)) as ApiResponse
			if (success) {
				setMessages(Number(chatId), data)
			}
		} catch (error) {
			console.error('获取消息列表失败:', error)
		}
	}, [chatId, setMessages])

	useEffect(() => {
		if (chatId) {
			fetchMessages()
		}
	}, [chatId, fetchMessages])

	// 发送消息
	const handleSendMessage = async () => {
		if (!messageInput.trim() || !activeChat) return

		try {
			frontendSendWsEvent(WSMessageType.MESSAGE, {
				chatId: Number(chatId),
				content: messageInput,
			})
			setMessageInput('')
		} catch (error) {
			console.error('发送消息失败:', error)
			message.error('发送消息失败，请重试')
		}
	}

	// 滚动到最新消息
	const scrollToBottom = () => {
		messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
	}

	// 监听消息变化，自动滚动
	useEffect(() => {
		scrollToBottom()
	}, [chatMessages])

	// 添加这个 useEffect 来确保组件只在客户端渲染
	useEffect(() => {
		setIsClient(true)
	}, [])

	return (
		<div className="flex h-full">
			<div className="flex-1 flex flex-col bg-gray-50">
				{/* 顶部区域 */}
				<div className="h-16 bg-white border-b flex items-center">
					<div className="px-6 flex items-center w-40">
						<span className="text-lg font-medium">{activeChat?.contact.nickname}</span>
						<Badge
							className="ml-2"
							status={activeChat?.contact.status === 'online' ? 'success' : 'default'}
							text={activeChat?.contact.status === 'online' ? '在线' : '离线'}
						/>
					</div>
					{/* 顶部可拖拽区域 */}
					<div
						className="flex-1 h-full cursor-grab active:cursor-grabbing"
						onMouseDown={handleMouseDown}
					/>
				</div>

				{/* 聊天区域 */}
				<div className="flex-1 overflow-y-auto p-6 bg-gray-50">
					{isClient && ( // 只在客户端渲染 List 组件
						<List
							dataSource={chatMessages}
							renderItem={(message) => {
								const isSelf = message.senderId === userInfo?.id
								return (
									<div className={`flex ${isSelf ? 'justify-end' : 'justify-start'} mb-4`}>
										{!isSelf && (
											<Avatar src={activeChat?.contact.avatar} size={40} className="mr-2 mt-1" />
										)}
										<div
											className={`max-w-[70%] px-4 py-2 rounded-lg ${
												isSelf ? 'bg-blue-500 text-white' : 'bg-white'
											}`}
										>
											{message.content}
										</div>
										{isSelf && (
											<Avatar
												src={userInfo?.avatar || '/default-avatar.png'}
												size={40}
												className="ml-2 mt-1"
											/>
										)}
									</div>
								)
							}}
						/>
					)}
					<div ref={messagesEndRef} />
				</div>

				{/* 输入区域 */}
				<div className="h-60 bg-white border-t px-6 py-4">
					<div className="flex items-center gap-2 mb-3">
						<Button type="text" icon={<SmileOutlined />} />
						<Button type="text" icon={<PictureOutlined />} />
						<Button type="text" icon={<FileOutlined />} />
					</div>
					<div className="flex gap-2">
						<Input.TextArea
							value={messageInput}
							onChange={(e) => setMessageInput(e.target.value)}
							onPressEnter={(e) => {
								if (!e.shiftKey) {
									e.preventDefault()
									handleSendMessage()
								}
							}}
							placeholder="输入消息..."
							autoSize={{ minRows: 6, maxRows: 6 }}
							className="flex-1"
						/>
						<Button
							type="primary"
							icon={<SendOutlined />}
							onClick={handleSendMessage}
							className="self-end"
						>
							发送
						</Button>
					</div>
				</div>
			</div>
		</div>
	)
}
